const getLocal = (key: string, emptyValue?: any) => {
  const item = localStorage.getItem(key);
  if (item) {
    try {
      const data = JSON.parse(item);
      return data;
    } catch (e) {
      return item;
    }
  }
  return emptyValue ? emptyValue : null;
};

const saveLocal = (key: string, value: any) => {
  localStorage.setItem(key, JSON.stringify(value));
};

const toTxt = (content: string, options: { name: string; suffix: string }) => {
  const { name, suffix } = options;
  const blob = new Blob([content], {
    type: 'text/plain;charset=utf-8',
  }); // 把数据转化成blob对象
  const file = new File([blob], `${name}.${suffix}`, {
    lastModified: Date.now(),
  });
  return file;
};

const download = (file: File, filename: string) => {
  const element = document.createElement('a');
  const objectUrl = URL.createObjectURL(file);

  element.href = objectUrl;
  element.download = filename;
  document.body.appendChild(element);
  element.click();
  document.body.removeChild(element);

  URL.revokeObjectURL(objectUrl);
};

const upload = (options: {
  onLoad?: (data: string) => void;
  onError: (e: string) => void;
  onFileLoad?: (f: any) => void;
  typeRule: string[];
}) => {
  const { onLoad, onError, typeRule, onFileLoad } = options;

  const fileEntry = document.createElement('input');
  fileEntry.setAttribute('type', 'file');
  fileEntry.setAttribute('accept', typeRule.map((i) => `.${i}`).join(','));
  fileEntry.style.display = 'none';
  fileEntry.onchange = function () {
    const _this = this as any;
    const file = _this.files[0];
    /**合法性校验**/
    if (file === undefined) {
      _this.value = '';
      onError('未选择文件或文件不合法');
      return;
    }
    onFileLoad?.(file);
    const reader = new FileReader();
    reader.readAsText(file);
    reader.onload = function () {
      fileEntry.value = '';
      onLoad?.(this.result as string);
    };
  };
  fileEntry.click();
};

export { saveLocal, getLocal, toTxt, download, upload };
